import { wxLogin } from '@/api/api';
import Toast from '@vant/weapp/toast/toast';
import { globalRouteGuard } from "@/utils/auth";

Page({
  data: {
    isLogin: false,
    defaultAvatar: '',
    userInfo: {},
    menus: [
      { icon: 'user-o', text: '个人信息', path: '/pages/editUserInfo/editUserInfo' },
      { icon: 'chart-trending-o', text: '借阅统计', path: '/pages/loanRecords/loanRecords' },
      { icon: 'setting-o', text: '系统设置' },
      { icon: 'question-o', text: '退出登录' },
      { icon: 'info-o', text: '关于我们', path: '/pages/aboutUs/aboutUs' }
    ]
  },
  onMenuTap(e) {
    const { index } = e.currentTarget.dataset;
    const { path } = this.data.menus[index];
    console.log(path);
    wx.navigateTo({
      url: path
    })
    switch (index) {
      case 3:
        this.logout();
        break;
        case 4: 

      default: break;
    }
  },
  onShow() {
    this.setData({
      isLogin: !!(getApp().Authorization),
      defaultAvatar: '../../assets/images/avatar.jpg',
      userInfo: getApp().userInfo
    })
    console.log(this.data.userInfo.avatar)
  },
  //进行登录
  onLoginTap() {
    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          // 调用后端 wxLogin API，传递 code
          wxLogin(loginRes.code)
            .then((res) => {
              if (res.code === 200) {
                // 登录成功，保存 token
                //获取用户信息
                const { token, ...rest } = res.data;
                getApp().Authorization = res.data.token;
                getApp().userInfo = rest;
                // 本地持久化保存
                wx.setStorageSync('Authorization', res.data.token);
                wx.setStorageSync('userInfo', rest);
                this.setData({
                  isLogin: true,
                  userInfo: rest
                });
                Toast.success('登录成功');
              } else {
                Toast.fail(res.message || '登录失败');
              }
            })
            .catch(() => {
              Toast.fail('网络错误');
            });
        } else {

          Toast.fail('获取code失败');
        }
      },
      fail: () => {
        Toast.fail('微信登录失败');
      }
    });
  },
  //退出登录
  logout() {
    if (!getApp().isLogin()) return Toast.fail('您尚未登录')
    wx.removeStorageSync('Authorization');
    wx.removeStorageSync('userInfo');
    getApp().Authorization = '';
    getApp().userInfo = {};
    this.setData({
      isLogin: false,
      userInfo: {}
    });
    Toast.success('退出登录成功');
  }
});